import {history, post, message, get} from '@/utils/utils'

const management = {
  namespaced: true,
  state: {
    list: [],
    sameNameList: [],
    page: 1,
    tradeCount: 0.00,
    hasData: true,
    pageNum: 1
  },

  mutations: {
    save(state, { field, payload }) {
      if (Object.prototype.toString.call(payload) === '[object Object]') {
        state[field] = { ...state[field], ...payload }
      } else {
        state[field] = payload
      }
    }
  },

  actions: {
    getList({ commit, state, dispatch }, {type, pageNum = 1, search = ''}) {
      const apis = {
        'agent': '/agt/agenttransactioncumulative/getAgentTurnover',
        'merchant': '/mec/merchanttransactioncumulative/getMecTurnover'
      }

      get({api: apis[type],
        data: {
          current: pageNum,
          size: 10,
          search
        },
        success: ({data}) => {
          const {pages, records} = data
          const {list, sameNameList} = state
          let recordList = list

          if (sameNameList.length > 0) {
            records.forEach(record => {
              if (sameNameList.includes(record.mno)) {
                record.isSameName = true
              }
            })
          }

          if (pageNum > 1) {
            recordList = recordList.concat(records)
          } else {
            recordList = records || []
            commit('save', {field: 'hasData', payload: true})
          }

          if (pages === pageNum || pages === 0) commit('save', {field: 'hasData', payload: false})

          commit('save', {field: 'pageNum', payload: pageNum})
          commit('save', {field: 'list', payload: recordList})
        }})
    },
    getMecTradeTotal({ commit }) {
      get({api: '/mec/merchanttransactioncumulative/getMecTurnoverByAgentNo',
        success: ({data}) => {
          const {mount} = data
          commit('save', {field: 'tradeCount', payload: mount})
        }})
    },

    getSameNameList({ commit }) {
      return post({ api: '/agt/agenttransferhis/sameNameMercList',
        success: ({data}) => {
          commit('save', {field: 'sameNameList', payload: data || []})
        }
      })
    },

    sameNameTransfer({ commit, state }, {mno, index}) {
      post({
        api: `/agt/agenttransferhis/sameNameMercTransfer?mno=${mno}`,
        success: ({data}) => {
          message.info('划拨成功')

          const {list} = state

          list[index].isSameName = undefined

          commit('save', {field: 'list', payload: list})
        }
      })
    }
  }
}

export default management
